﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading;

namespace AntBot
{
	public static class Logger
	{
		private const string FILE_NAME = "botlog.txt";

		static Logger()
		{
			Enabled = true;
			LogToConsole = false;
		}

		public static bool LogToConsole { get; set; }
		public static bool Enabled { get; set; }

		private static FileStream fileStream;

		public static void Log(List<Move> moveList)
		{
			#if LOG
			if (!Enabled) return;
			if (moveList == null) return;

			if (moveList.Count == 0)
			{
				Log("empty movelist");
				return;
			}

			Log(moveList.Count + " moves: ");
			foreach (Move move in moveList)
			{
				Log("\t" + move);
			}
			#endif
		}

		public static void Log(string format, params object[] arg)
		{
			Log(string.Format(Thread.CurrentThread.CurrentCulture, format, arg));
		}

		public static void Log(string message)
		{
			#if LOG
			if (!Enabled) return;

			if (fileStream == null)
				fileStream = new FileStream(FILE_NAME, FileMode.Create, FileAccess.Write);

			int length = message.IndexOf("\n\r");
			string modifiedMessage = length > 0 ? message.Substring(0, length) : message;

			byte[] byteData = Encoding.Default.GetBytes(
				modifiedMessage + "\n\r");

			if (LogToConsole)
				Console.WriteLine(modifiedMessage);

			if (fileStream != null)
			{
				fileStream.Write(byteData, 0, byteData.Length);
				fileStream.Flush();
			}

			if (length <= 0) return;
			Log(message.Substring(length + 1, message.Length - length - 1));
			#endif
		}

		public static void Close()
		{
			//fileStream.Close();
		}
	}
}